<template>
  <div class="profile-edit">
    <div class="header">
      <h2>编辑个人信息</h2>
      <div class="header-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>

    <div class="content-container">
      <el-card>
        <el-form :model="userForm" :rules="formRules" ref="userFormRef" label-width="100px" class="user-form">
          <!-- 头像和基本信息区域 -->
          <div class="profile-header-section">
            <div class="profile-header-section">
              <div class="avatar-section">
                <el-avatar :size="120" :src="getAvatarUrl(userForm.avatar)" :alt="userForm.name">
                  <img :src="getAvatarUrl(userForm.avatar)" :alt="userForm.name" @error="handleAvatarError" />
                </el-avatar>
                <el-button type="primary" size="small" class="avatar-btn" @click="handleUploadAvatar">
                  更换头像
                </el-button>
                <input type="file" ref="avatarInput" style="display: none" accept="image/*"
                  @change="handleAvatarChange" />
              </div>
            </div>
            <div class="basic-info-section">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" disabled />
              </el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input v-model="userForm.name" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userForm.gender" class="gender-group">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>

          <!-- 联系方式区域 -->
          <div class="contact-section">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </div>

          <!-- 其他信息区域 -->
          <div class="other-info-section">
            <el-form-item label="角色">
              <el-input v-model="userForm.roleName" disabled />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-input :value="formatDate(userForm.createTime)" disabled />
            </el-form-item>
          </div>

          <!-- 个人简介 -->
          <el-form-item label="个人简介">
            <el-input v-model="userForm.bio" type="textarea" :rows="4" placeholder="请输入个人简介" />
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/api/profile'

const router = useRouter()

// 用户表单
const userForm = reactive({
  id: '',
  username: '',
  name: '',
  gender: 1,
  email: '',
  phone: '',
  roleName: '',
  avatar: '',
  bio: '',
  createTime: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const userFormRef = ref(null)
const avatarInput = ref(null)

// 获取用户信息
// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    console.log('获取用户信息成功:', res)

    if (res && res.code === 200) {
      const data = res.data
      console.log('用户信息:', data)
      // 逐个字段赋值
      userForm.id = data.id || ''
      userForm.username = data.username || ''
      userForm.name = data.name || ''
      userForm.gender = data.gender ?? 1
      userForm.email = data.email || ''
      userForm.phone = data.phone || ''
      userForm.roleName = data.roleName || '用户'
      userForm.avatar = data.avatar || '/default avatar.png' // 添加这行
      userForm.bio = data.bio || ''
      userForm.createTime = data.created || ''
      // 如果你有 avatarUrl 这个 ref，也需要更新
      // avatarUrl.value = data.avatar || '/default avatar.png'
    } else {
      ElMessage.error(res?.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取头像完整URL
const getAvatarUrl = (avatarPath) => {
  if (!avatarPath) {
    return '/default_avatar.png' // 默认头像
  }
  
  // 如果已经是完整URL，直接返回
  if (avatarPath.startsWith('http')) {
    return avatarPath
  }
  
  // 如果是本地路径，添加基础URL
  if (avatarPath.startsWith('/')) {
    return `http://localhost:8085${avatarPath}`
  }
  
  // 如果是文件名，添加静态资源路径
  return `http://localhost:8085/static/${avatarPath}`
}

// 头像加载失败处理
const handleAvatarError = (event) => {
  console.log('头像加载失败，使用默认头像')
  event.target.src = '/default_avatar.png'
}


// 上传头像
const handleUploadAvatar = () => {
  avatarInput.value.click()
}

// 头像文件变化
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)

    const res = await uploadAvatar(formData)

    if (res) {
      userForm.avatar = res.url || URL.createObjectURL(file)
      ElMessage.success('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
    // 本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      userForm.avatar = e.target.result
    }
    reader.readAsDataURL(file)
  }

  // 清空文件输入
  event.target.value = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()

    const res = await updateUserInfo(userForm)
    if (res) {
      ElMessage.success('个人信息更新成功')
      router.push('/profile')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  }
}

// 取消编辑
const handleCancel = () => {
  router.push('/profile')
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
/* 简化的全局样式 */
.profile-edit {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

/* 头部样式优化 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 24px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-bottom: 2px solid #e6e9ed;
}

.header h2 {
  font-size: 24px;
  color: #1f2937;
  margin: 0;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  padding: 8px 20px;
  font-size: 14px;
}

/* 内容容器 */
.content-container {
  margin-top: 0;
}

/* 卡片样式 */
.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  background-color: #ffffff;
}

.el-card__body {
  padding: 24px;
}

/* 表单容器 */
.user-form {
  max-width: 800px;
  margin: 0 auto;
}

/* 表单分组样式 - 关键的布局改进 */
.profile-header-section {
  display: flex;
  align-items: flex-start;
  gap: 40px;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.basic-info-section {
  flex: 1;
  min-width: 0;
}

.contact-section,
.other-info-section {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.contact-section .el-form-item,
.other-info-section .el-form-item {
  flex: 1;
  min-width: 250px;
  margin-bottom: 0;
}

/* 表单元素样式 */
.user-form .el-form-item {
  margin-bottom: 20px;
}

.user-form .el-form-item__label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

/* 输入框样式 */
.user-form .el-input .el-input__inner {
  border-radius: 4px;
  height: 40px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
}

.user-form .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 文本域样式 */
.user-form .el-textarea .el-textarea__inner {
  min-height: 100px;
  resize: vertical;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

/* 禁用字段样式 */
.user-form .el-input--disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
  border-color: #dcdfe6;
}

/* 头像样式 */
.avatar-section .el-avatar {
  border: 3px solid #f0f2f5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 头像上传按钮 */
.avatar-btn {
  background-color: #409eff;
  border: none;
  color: white;
  padding: 8px 16px;
  font-size: 13px;
  border-radius: 4px;
  transition: all 0.3s;
}

.avatar-btn:hover {
  background-color: #66b1ff;
}

/* 性别选择器 */
.gender-group {
  display: flex;
  gap: 20px;
}

/* 响应式设计 - 重新设计的移动端布局 */
@media (max-width: 768px) {
  .profile-edit {
    padding: 12px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 16px;
  }

  .header h2 {
    font-size: 20px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .el-card__body {
    padding: 16px;
  }

  /* 关键的移动端布局改进 */
  .profile-header-section {
    flex-direction: column;
    align-items: center;
    gap: 20px;
    text-align: center;
  }

  .basic-info-section {
    width: 100%;
  }

  .contact-section,
  .other-info-section {
    flex-direction: column;
    gap: 16px;
  }

  .contact-section .el-form-item,
  .other-info-section .el-form-item {
    min-width: auto;
  }

  .gender-group {
    justify-content: center;
  }

  .user-form .el-form-item {
    margin-bottom: 16px;
  }

  .user-form .el-input .el-input__inner {
    height: 36px;
    font-size: 13px;
  }
}

/* 平板响应式 */
@media (min-width: 769px) and (max-width: 1024px) {
  .user-form {
    max-width: 100%;
  }

  .profile-header-section {
    gap: 30px;
  }

  .contact-section .el-form-item,
  .other-info-section .el-form-item {
    min-width: 200px;
  }
}

/* 打印样式 */
@media print {
  .profile-edit {
    background: white;
    padding: 0;
  }

  .header {
    box-shadow: none;
    border: 1px solid #ddd;
  }

  .header-actions {
    display: none;
  }

  .el-card {
    box-shadow: none;
    border: 1px solid #ddd;
  }

  .avatar-btn {
    display: none;
  }
}
</style>